"""
分页相关工具函数
"""
from flask import request, url_for

def get_pagination_params():
    """获取分页参数"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    
    # 限制每页最大条数，防止资源滥用
    if per_page > 100:
        per_page = 100
    
    return page, per_page

def get_paginated_response(schema, pagination, endpoint, **kwargs):
    """
    构建带有分页信息的响应
    
    Args:
        schema: Marshmallow模式
        pagination: SQLAlchemy分页对象
        endpoint: 路由端点名
        **kwargs: URL参数
    
    Returns:
        dict: 包含数据和分页信息的字典
    """
    data = schema.dump(pagination.items)
    
    links = {}
    
    # 添加上一页链接
    if pagination.has_prev:
        kwargs['page'] = pagination.prev_num
        links['prev'] = url_for(endpoint, **kwargs)
    
    # 添加下一页链接
    if pagination.has_next:
        kwargs['page'] = pagination.next_num
        links['next'] = url_for(endpoint, **kwargs)
    
    # 添加首页链接
    kwargs['page'] = 1
    links['first'] = url_for(endpoint, **kwargs)
    
    # 添加尾页链接
    kwargs['page'] = pagination.pages
    links['last'] = url_for(endpoint, **kwargs)
    
    response = {
        'data': data,
        'meta': {
            'total': pagination.total,
            'pages': pagination.pages,
            'page': pagination.page,
            'per_page': pagination.per_page
        },
        'links': links
    }
    
    return response 